﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using Microsoft.Phone.Controls.Maps;
using System.Xml.Linq;
using System.Windows.Media.Imaging;

//--------------------- Copyright Block ----------------------
/*


C# Code By: Tareq Ateik

License: GNU General Public License, ver 3

TERMS OF USE:
	Permission is granted to use this code, with or
	without modification, in any website or application
	provided that credit is given to the original work
	with a link back to ateik.me

This program is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY.

PLEASE DO NOT REMOVE THIS COPYRIGHT BLOCK.

*/

namespace PrayerTime
{
    public partial class FindMosque : PhoneApplicationPage
    {
        #region
        GeoCoordinateWatcher Watcher;
        double Lon, Lat;
        WebClient GooglePlaces = new WebClient();
        WebClient RouteWebClient = new WebClient();
        MapLayer MapLayer = new MapLayer();
        MapLayer TextLayer = new MapLayer();
        MapPolyline Route = new MapPolyline();
        List<Mosque> Mosques = new List<Mosque>();

        private const string httpQuery = "https://maps.googleapis.com/maps/api/place/search/xml?";
        private const string GoogleAPIKey = "YOUR_GOOGLE_API";
        private const string BingAPIKey = "YOUR_BING_API";
        #endregion
        public FindMosque()
        {
            InitializeComponent();

            GooglePlaces.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GooglePlaces_DownloadStringCompleted);
            mapBing.MapZoom += new EventHandler<MapZoomEventArgs>(mapBing_MapZoom);
            mapBing.Children.Add(MapLayer);
            mapBing.Children.Add(TextLayer);
            Route.Stroke = new SolidColorBrush(Colors.Blue);
            Route.Opacity = 0.65;
            Route.StrokeThickness = 5;
            MapLayer.Children.Add(Route);
            mapBing.ZoomLevel = 12;
        }
        void mapBing_MapZoom(object sender, MapZoomEventArgs e)
        {
            if (mapBing.ZoomLevel < 8)
                TextLayer.Visibility = System.Windows.Visibility.Collapsed;
            else
                TextLayer.Visibility = System.Windows.Visibility.Visible;
        }
        void GooglePlaces_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            XDocument document = XDocument.Parse(e.Result);
            var data = from query in document.Descendants("result")
                       select new Mosque
                       {
                           Name = (string)query.Element("name"),
                           Vicinity = (string)query.Element("vicinity"),
                           Location = new GeoCoordinate((double)query.Element("geometry").Element("location").Element("lat"), (double)query.Element("geometry").Element("location").Element("lng"))
                       };

            Mosques = data.ToList<Mosque>();
            GeoCoordinate temp = new GeoCoordinate();
            foreach (Mosque m in data)
            {
                MapLayer.AddChild(new Image() { Source = new BitmapImage(new Uri("mosque.png", UriKind.Relative)), Width=50,Height=50 }, m.Location);
                temp = m.Location;
                TextLayer.AddChild(new TextBlock() { Text = m.Name, Foreground = new SolidColorBrush(Colors.Black) }, m.Location);
            }

            progressBar.Visibility = System.Windows.Visibility.Collapsed;
            progressBar.IsIndeterminate = false;
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            // get the location
            if (Watcher == null)
            {
                Watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default); 
                Watcher.MovementThreshold = 20; // Use MovementThreshold to ignore noise in the signal.
                Watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            }
            Watcher.Start();
            progressBar.Visibility = System.Windows.Visibility.Visible;
            progressBar.IsIndeterminate = true;
        }
        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            if (e.Status == GeoPositionStatus.Ready)
            {
                GeoCoordinate co = Watcher.Position.Location;
                Lon = co.Longitude;
                Lat = co.Latitude;
                co = new GeoCoordinate(Lat, Lon);
                mapBing.Center = co;

                MapLayer.AddChild(new Pushpin(), co);
                TextLayer.AddChild(new TextBlock() { Text = "Your place", Foreground = new SolidColorBrush(Colors.Black) }, co);
                GooglePlaces.DownloadStringAsync(new Uri(httpQuery + "location="+Lat+","+Lon+"&radius=500"+"&name=mosque&sensor=false&key=" + GoogleAPIKey));


                Watcher.Stop();
                
            }
        }
        private void radListBoxList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (radListBoxList.SelectedItem != null)
            {
                mapBing.Center = ((Mosque)radListBoxList.SelectedItem).Location;
                mapBing.ZoomLevel = 15;
                radWindowList.IsOpen = false;
                radListBoxList.ItemsSource = null;

            }
        }
        private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)
        {
            radListBoxList.ItemsSource = Mosques;
            radWindowList.IsOpen = true;
        }
        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            mapBing.Center = new GeoCoordinate(Lat, Lon);
            mapBing.ZoomLevel = 12;
        }
    }
}